package pl.agh.pp.zephyr.utils.parser;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import pl.agh.pp.zephyr.utils.parser.MCUStatus.Client;
import pl.agh.pp.zephyr.utils.parser.MCUStatus.Room;

public class HTMLParser {

	private static NodeList parse(String address) {
		Parser parser = null;
		NodeList list = null;
		try {
			parser = new Parser(address);
			list = parser.parse(null);
		} catch (ParserException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	private static String[] getStatusTableStringArray(String address) {
		Node node = parse(address).elementAt(0).getChildren().elementAt(3);
		String[] statusTableStringArray = null;
		if (node != null) {
			String statusTableString = node.getChildren().elementAt(8)
					.getChildren().elementAt(1).getChildren().elementAt(3)
					.toHtml();
			statusTableStringArray = statusTableString.split("<tr>");
		}
		return statusTableStringArray;
	}

	public static MCUStatus getMCUStatus(String address) {
		MCUStatus mcuStatus = new MCUStatus();
		String[] statusTableStringArray = getStatusTableStringArray(address);
		Room currentRoom = null;
		if (statusTableStringArray != null) {
			for (String row : statusTableStringArray) {
				if (row.startsWith("<th>")) {
					continue;
				}
				String[] elements = row.split("<td>");
				if (elements.length >= 6 && currentRoom != null) {
					String clientName = elements[1].substring(0,
							elements[1].length() - 5);
					String duration = elements[2].substring(0,
							elements[2].length() - 5);
					String codec = elements[3].substring(0,
							elements[3].length() - 5);
					String rtpPacketsBytestx = elements[4].substring(0,
							elements[4].length() - 5);
					String rtpPacketsBytesrx = elements[5].substring(0,
							elements[5].length() - 5);
					Client client = mcuStatus.new Client(clientName, duration,
							codec, rtpPacketsBytestx, rtpPacketsBytesrx);
					currentRoom.addClient(client);
				}

				String lastElement = elements[elements.length - 1];
				if (lastElement.endsWith("<table border=1>")) {
					String roomName = lastElement.substring(
							lastElement.indexOf("<TD>") + 4,
							lastElement.lastIndexOf("</TD>"));
					if(roomName.startsWith("MCU") == false) {
						currentRoom = mcuStatus.new Room(roomName);
						mcuStatus.addRoom(currentRoom);
					}
					// System.out.println("roomName: " + roomName);
				}

				// System.out.println("_____________");
				// for (String element : elements) {
				// System.out.println(element);
				// }
				// System.out.println("-------------");
			}
		}
		return mcuStatus;
	}
}
